package com.example.demo;

import com.jfinal.kit.Kv;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import org.noear.dami2.Dami;
import org.noear.dami2.bus.DamiBus;
import org.noear.dami2.bus.receivable.CallEventListener;

/**
 * @author airhead
 */
public class EventUtils {
    private static final DamiBus BUS = Dami.bus();

    public static void send(final String topic, final Kv event) throws ExecutionException, InterruptedException {
        sendAndSubscribe(
                topic,
                event,
                ret -> {
                    System.out.println("ret : " + ret);
                });
    }

    public static boolean sendAndSubscribe(String topic, Kv ev, Consumer<Ret> consumer) {
        return BUS.<Kv, Ret>callAsResult(topic, ev).thenConsume(r -> {
            r.getPayload().getSink().thenAccept(consumer);
        }).getHandled();
    }

    public static Ret call(final String topic, final Kv event) throws ExecutionException, InterruptedException {
        return BUS.<Kv, Ret>call(topic, event).get();
    }

    public static void listen(final String topic, final CallEventListener<Kv, Ret> listener) {
        BUS.listen(topic, 0, listener);
    }

    public static void listen(final String topic, final int index, final CallEventListener<Kv, Ret> listener) {
        BUS.listen(topic, index, listener);
    }

    public static void unlisten(final String topic, final CallEventListener<Kv, Ret> listener) {
        BUS.unlisten(topic, listener);
    }

    public static void unlisten(final String topic) {
        BUS.unlisten(topic);
    }
}
